package platform

import (
	"fmt"
	"net/http"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	platformCommon "gitee.com/wangshh_123/cross-pay-go/src/platform/common"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/integration"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/auth"
	utilsCommon "gitee.com/wangshh_123/cross-pay-go/src/utils/common"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// CardDetailController 统一的卡片详情控制器
// 使用工厂模式处理不同平台的卡片详情查询
type CardDetailController struct {
	platformManager *integration.PlatformManager
	db              *gorm.DB
}

// NewCardDetailController 创建卡片详情控制器实例
func NewCardDetailController() *CardDetailController {
	return &CardDetailController{
		platformManager: integration.GetGlobalPlatformManager(),
		db:              database.DB,
	}
}

// GetCardDetail 获取卡片详情信息
// 根据用户的平台类型自动选择对应的平台进行查询
func (c *CardDetailController) GetCardDetail(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		utilsCommon.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 获取当前用户ID
	var userID int64
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			userID = authClaims.UserID
		}
	}

	if userID == 0 {
		utilsCommon.Error(ctx, http.StatusUnauthorized, "user_not_found", nil)
		return
	}

	// 获取卡片ID - 支持两种参数名称
	cardID := ctx.Query("cardId")
	if cardID == "" {
		cardID = ctx.Query("card_id") // 向后兼容
	}
	if cardID == "" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "card_id_required", nil)
		return
	}

	// 构建卡详情查询请求
	request := &platformCommon.CardDetailRequest{
		CardID: cardID,
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequest(ctx.Request.Context(), platformInfo.PlatformType, "card_detail", request)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "get_card_detail_failed", err)
		return
	}

	// 尝试将结果转换为CardDetailResponse
	if cardDetailResponse, ok := result.(*platformCommon.CardDetailResponse); ok {
		// 检查数据库中是否存在该卡片记录
		var existingCard models.UserCard
		err := c.db.Where("card_id = ?", cardID).First(&existingCard).Error

		if err != nil {
			if err == gorm.ErrRecordNotFound {
				// 记录不存在，创建新记录
				fmt.Printf("[CardDetailController] 卡片 %s 在数据库中不存在，开始创建新记录\n", cardID)

				// 从卡详情响应中提取信息
				cardDetail := cardDetailResponse.Data

				// 创建新的用户卡记录
				newUserCard := models.UserCard{
					UserID:     userID,
					CardID:     cardID,
					Platform:   platformInfo.PlatformType,
					CardStatus: c.convertCardStatus(cardDetail.CardStatus),
					CardBin:    c.extractCardBin(cardDetail.CardNo),
					CardType:   cardDetail.CardType,
					NikeName:   cardDetail.Nickname,
					CreatedAt:  time.Now(),
					UpdatedAt:  time.Now(),
				}

				// 保存到数据库
				if err := c.db.Create(&newUserCard).Error; err != nil {
					fmt.Printf("[CardDetailController] 创建卡片记录失败: %v\n", err)
					// 不中断流程，继续返回卡详情
				} else {
					fmt.Printf("[CardDetailController] 成功创建卡片记录: CardID=%s, Platform=%s\n",
						cardID, platformInfo.PlatformType)
				}
			} else {
				// 其他数据库错误
				fmt.Printf("[CardDetailController] 查询卡片记录时发生错误: %v\n", err)
			}
		} else {
			// 记录存在，更新信息
			fmt.Printf("[CardDetailController] 卡片 %s 在数据库中存在，更新信息\n", cardID)

			cardDetail := cardDetailResponse.Data

			// 更新卡片信息
			updates := map[string]interface{}{
				"card_status": c.convertCardStatus(cardDetail.CardStatus),
				"card_bin":    c.extractCardBin(cardDetail.CardNo),
				"cardType":    cardDetail.CardType,
				"nike_name":   cardDetail.Nickname,
				"updated_at":  time.Now(),
			}

			if err := c.db.Model(&existingCard).Updates(updates).Error; err != nil {
				fmt.Printf("[CardDetailController] 更新卡片记录失败: %v\n", err)
			} else {
				fmt.Printf("[CardDetailController] 成功更新卡片记录: CardID=%s\n", cardID)
			}

			// 打印限额信息用于调试
			fmt.Printf("[CardDetailController] 卡片 %s 限额信息: TotalTransactionLimit=%d, MaxOnDaily=%d, AvailableTransactionLimit=%d\n",
				cardID, cardDetail.TotalTransactionLimit, cardDetail.MaxOnDaily, cardDetail.AvailableTransactionLimit)
		}
	}

	// 返回成功响应
	utilsCommon.Success(ctx, gin.H{
		"platform": platformInfo.PlatformType,
		"data":     result,
	})
}

// GetCardDetailByPlatform 根据指定平台获取卡片详情信息
// 允许管理员或高级用户查询指定平台的卡片详情信息
func (c *CardDetailController) GetCardDetailByPlatform(ctx *gin.Context) {
	// 从URL参数获取平台类型
	platformType := ctx.Param("platform")
	if platformType == "" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "platform_parameter_required", nil)
		return
	}

	// 获取当前用户ID
	var userID int64
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			userID = authClaims.UserID
		}
	}

	if userID == 0 {
		utilsCommon.Error(ctx, http.StatusUnauthorized, "user_not_found", nil)
		return
	}

	// 获取卡片ID - 支持两种参数名称
	cardID := ctx.Query("cardId")
	if cardID == "" {
		cardID = ctx.Query("card_id") // 向后兼容
	}
	if cardID == "" {
		utilsCommon.Error(ctx, http.StatusBadRequest, "card_id_required", nil)
		return
	}

	// 构建卡详情查询请求
	request := &platformCommon.CardDetailRequest{
		CardID: cardID,
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequest(ctx.Request.Context(), platformType, "card_detail", request)
	if err != nil {
		utilsCommon.Error(ctx, http.StatusInternalServerError, "get_card_detail_failed", err)
		return
	}

	// 尝试将结果转换为CardDetailResponse
	if cardDetailResponse, ok := result.(*platformCommon.CardDetailResponse); ok {
		// 检查数据库中是否存在该卡片记录
		var existingCard models.UserCard
		err := c.db.Where("card_id = ?", cardID).First(&existingCard).Error

		if err != nil {
			if err == gorm.ErrRecordNotFound {
				// 记录不存在，创建新记录
				fmt.Printf("[CardDetailController] 卡片 %s 在数据库中不存在，开始创建新记录\n", cardID)

				// 从卡详情响应中提取信息
				cardDetail := cardDetailResponse.Data

				// 创建新的用户卡记录
				newUserCard := models.UserCard{
					UserID:     userID,
					CardID:     cardID,
					Platform:   platformType,
					CardStatus: c.convertCardStatus(cardDetail.CardStatus),
					CardBin:    c.extractCardBin(cardDetail.CardNo),
					CardType:   cardDetail.CardType,
					NikeName:   cardDetail.Nickname,
					CreatedAt:  time.Now(),
					UpdatedAt:  time.Now(),
				}

				// 保存到数据库
				if err := c.db.Create(&newUserCard).Error; err != nil {
					fmt.Printf("[CardDetailController] 创建卡片记录失败: %v\n", err)
					// 不中断流程，继续返回卡详情
				} else {
					fmt.Printf("[CardDetailController] 成功创建卡片记录: CardID=%s, Platform=%s\n",
						cardID, platformType)
				}
			} else {
				// 其他数据库错误
				fmt.Printf("[CardDetailController] 查询卡片记录时发生错误: %v\n", err)
			}
		} else {
			// 记录存在，更新信息
			fmt.Printf("[CardDetailController] 卡片 %s 在数据库中存在，更新信息\n", cardID)

			cardDetail := cardDetailResponse.Data

			// 更新卡片信息
			updates := map[string]interface{}{
				"card_status": c.convertCardStatus(cardDetail.CardStatus),
				"card_bin":    c.extractCardBin(cardDetail.CardNo),
				"cardType":    cardDetail.CardType,
				"nike_name":   cardDetail.Nickname,
				"updated_at":  time.Now(),
			}

			if err := c.db.Model(&existingCard).Updates(updates).Error; err != nil {
				fmt.Printf("[CardDetailController] 更新卡片记录失败: %v\n", err)
			} else {
				fmt.Printf("[CardDetailController] 成功更新卡片记录: CardID=%s\n", cardID)
			}

			// 打印限额信息用于调试
			fmt.Printf("[CardDetailController] 卡片 %s 限额信息: TotalTransactionLimit=%d, MaxOnDaily=%d, AvailableTransactionLimit=%d\n",
				cardID, cardDetail.TotalTransactionLimit, cardDetail.MaxOnDaily, cardDetail.AvailableTransactionLimit)
		}
	}

	// 返回成功响应
	utilsCommon.Success(ctx, gin.H{
		"platform": platformType,
		"data":     result,
	})
}

// convertCardStatus 转换卡状态格式
func (c *CardDetailController) convertCardStatus(apiStatus string) string {
	switch apiStatus {
	case "NORMAL", "ACTIVE":
		return "active"
	case "FROZEN":
		return "frozen"
	case "CLOSED", "CANCELLED":
		return "closed"
	case "INACTIVE":
		return "inactive"
	default:
		return "active"
	}
}

// extractCardBin 从卡号中提取卡BIN
func (c *CardDetailController) extractCardBin(cardNo string) string {
	if len(cardNo) >= 6 {
		return cardNo[:6]
	}
	return "111111" // 默认BIN
}

// GetSupportedPlatforms 获取支持卡详情查询的平台列表
func (c *CardDetailController) GetSupportedPlatforms(ctx *gin.Context) {
	// 获取平台信息
	supportedPlatforms := c.platformManager.GetFactory().GetSupportedPlatforms()

	platforms := make([]gin.H, 0, len(supportedPlatforms))
	for _, platformID := range supportedPlatforms {
		platformInfo, err := c.platformManager.GetPlatformInfo(platformID)
		if err != nil {
			continue
		}

		// 检查平台是否支持卡详情查询
		supportsCardDetail := platformID == "photonpay" || platformID == "hlpay" // 两个平台都支持卡详情查询

		platforms = append(platforms, gin.H{
			"platform":             platformID,
			"supports_card_detail": supportsCardDetail,
			"supported_features":   platformInfo["supported_operations"],
			"config":               platformInfo["config"],
		})
	}

	utilsCommon.Success(ctx, gin.H{
		"platforms": platforms,
		"total":     len(platforms),
	})
}
